package com.zhp.utils;

import cn.hutool.core.collection.CollUtil;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author zhanghp
 * @since 2024/5/27 14:34
 */
public class CollectUtils {

    /**
     * list转map
     *
     * @param from 集合
     * @param keyFunc 父类func
     * @return map
     * @param <T> 父类
     * @param <K> 子类
     */
    public static <T, K> Map<K, T> convertMap(Collection<T> from, Function<T, K> keyFunc) {
        if (CollUtil.isEmpty(from)) {
            return new HashMap<>();
        }
        return convertMap(from, keyFunc, (e1, e2) -> e1);
    }

    public static <T, K> Map<K, T> convertMap(Collection<T> from, Function<T, K> keyFunc, BinaryOperator<T> binaryOperator) {
        if (CollUtil.isEmpty(from)) {
            return new HashMap<>();
        }
        return convertMap(from, keyFunc, binaryOperator, HashMap::new);
    }

    public static <T, K> Map<K, T> convertMap(Collection<T> from, Function<T, K> keyFunc, BinaryOperator<T> mergeOperator, Supplier<? extends Map<K, T>> supplier) {
        if (CollUtil.isEmpty(from)) {
            return supplier.get();
        }
        return convertMap(from, keyFunc, Function.identity(), mergeOperator, supplier);
    }

    public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc, BinaryOperator<V> mergeOperator, Supplier<? extends Map<K, V>> supplier) {
        if (CollUtil.isEmpty(from)) {
            return supplier.get();
        }
        return from.stream().collect(Collectors.toMap(keyFunc, valueFunc, mergeOperator, supplier));
    }
}
